package com.farm.wcp.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.farm.authority.FarmAuthorityService;
import com.farm.category.service.ClasstypeServiceInter;
import com.farm.core.page.ViewMode;
import com.farm.learn.domain.ex.ClassLearnView;
import com.farm.learn.domain.ex.HourView;
import com.farm.learn.service.ClasschapterServiceInter;
import com.farm.learn.service.ClasshourServiceInter;
import com.farm.learn.service.ClasstServiceInter;
import com.farm.learn.service.PlaytimeServiceInter;
import com.farm.learn.service.TopServiceInter;
import com.farm.learn.service.UserclassServiceInter;
import com.farm.sfile.WdapFileServiceInter;
import com.farm.social.domain.ex.ResourceView;
import com.farm.social.service.AppbindobjServiceInter;
import com.farm.social.service.FavoriteobjServiceInter;
import com.farm.web.WebUtils;
import com.farm.web.log.WcpLog;
import com.farm.wlp.events.EventHandLoader;
import com.farm.wuc.events.WucEventInfo;
import com.farm.wuc.events.WucEventModle;
import com.farm.wuc.events.WucEventRole;
import com.farm.wuc.events.WucEventUsers;
import com.wcp.question.service.QuestionServiceInter;

/**
 * 课时创建
 * 
 * @author autoCode
 * 
 */
@RequestMapping("/hourweb")
@Controller
public class HourWebController extends WebUtils {
	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(HourWebController.class);
	@Resource
	private QuestionServiceInter questionServiceImpl;
	@Resource
	private ClasstypeServiceInter classTypeServiceImpl;
	@Resource
	private ClasstServiceInter classTServiceImpl;
	@Resource
	private ClasschapterServiceInter classChapterServiceImpl;
	@Resource
	private ClasshourServiceInter classHourServiceImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	@Resource
	private TopServiceInter topServiceImpl;
	@Resource
	private UserclassServiceInter userClassServiceImpl;
	@Resource
	private AppbindobjServiceInter appbindObjServiceImpl;
	@Resource
	private PlaytimeServiceInter playTimeServiceImpl;
	@Resource
	private FavoriteobjServiceInter favoriteObjServiceImpl;
	/**
	 * 预览课程(不会触发进行学习)
	 * 
	 * @return
	 */
	@RequestMapping("/Pubview")
	public ModelAndView view(String classid, String hourid, String type, HttpSession session,
			HttpServletRequest request) {
		ViewMode view = ViewMode.getInstance();
		try {
			HourView hourview = null;
			if (!classTServiceImpl.isReadAble(classid, getCurrentUser(session))) {
				throw new RuntimeException("当前用户无查看权限!");
			}
			if (StringUtils.isBlank(hourid)) {
				hourview = classTServiceImpl.getFirstHourView(classid);
			} else {
				hourview = classTServiceImpl.getHourView(hourid);
			}
			ClassLearnView learnView = null;
			if (getCurrentUser(session) != null) {
				// 查询学习进度
				learnView = userClassServiceImpl.getClassLearnView(classid, getCurrentUser(session));
				hourview.getClassview().bind(learnView);
				view.putAttr("learnView", learnView);
			}
			// 加载课时的预览属性
			HourView.initClassHourAble(hourview.getClassview());
			if (learnView == null || !learnView.isLearned()) {
				// 未学习过
				if (!HourView.initHourViewAble(hourview).isViewAble()) {
					// 也不可预览
					return view.returnRedirectUrl("/classweb/Pubview.do?classid=" + classid);
				}
			}
			List<ResourceView> resources = appbindObjServiceImpl.getAppResource(hourview.getHour().getId());
			List<ResourceView> classResources = appbindObjServiceImpl.getAppResource(hourview.getHour().getClassid());
			resources = mergeClassToHourResources(resources, classResources);
			view.putAttr("resources", resources);
			// 加载课件播放资源(同时加载用户播放时间)
			loadPlayUrlAndPlayTime(view, hourview, session, request);
			// 加载课时说明
			if (hourview.getHour().getNoteid() != null) {
				String text = wdapFileServiceImpl.readFileToText(hourview.getHour().getNoteid());
				view.putAttr("text", text);
			} else {
				view.putAttr("text", null);
			}
			WcpLog.info(
					"预览课程:" + hourview.getClassview().getClasst().getName() + "/" + hourview.getHour().getTitle()
							+ (getCurrentUser(session) != null ? "【用戶】" + getCurrentUser(session).getName() : "【匿名】"),
					null, null);
			// 预览课时事件
			runEvent(hourview, session, request);
			return view.putAttr("hourview", hourview).returnModelAndView("web-simple/hour/hour-view");
		} catch (Exception e) {
			return view.setError(e.getMessage(), e).returnModelAndView("web-simple/simple-500");
		}
	}

	/**
	 * 加载课件播放资源(同时加载用户播放时长信息)
	 * 
	 * @param view
	 * @param hourview
	 * @return
	 */
	private ViewMode loadPlayUrlAndPlayTime(ViewMode view, HourView hourview, HttpSession session, HttpServletRequest request) {
		if (hourview.getFilebase().getExname().toUpperCase().equals("MP4")) {
			// 视频课件
			if (StringUtils.isNotBlank(hourview.getHour().getFileurl())) {
				view.putAttr("playUrl", hourview.getHour().getFileurl());
			} else {
				view.putAttr("playUrl", wdapFileServiceImpl.getPlayUrl(hourview.getFilebase().getId(), false));
			}
		}
		if (hourview.getFilebase().getExname().toUpperCase().equals("PDF")) {
			// PDF课件
			view.putAttr("viewUrl", wdapFileServiceImpl.getViewUrl(hourview.getFilebase().getId(), false));
			view.putAttr("playUrl", wdapFileServiceImpl.getPlayUrl(hourview.getFilebase().getId(), false));
		}
		// 处理用户视频播放状态
		String userkey = getCurrentIp(request);
		if (getCurrentUser(session) != null) {
			userkey = getCurrentUser(session).getId();
			playTimeServiceImpl.loadPlayCache();
		}
		hourview.setPlaytime(playTimeServiceImpl.getHourPlayTime(hourview.getHour().getId(), userkey));
		return view;
	}

	/**
	 * 记录课时事件
	 * 
	 * @param hourview
	 * @param session
	 * @param request
	 */
	private void runEvent(HourView hourview, HttpSession session, HttpServletRequest request) {
		try {
			EventHandLoader.getHandler().runEvent(//
					WucEventModle.HOUR_VIEW_S, //
					new WucEventInfo(hourview.getHour().getId(), hourview.getHour().getTitle()), //
					new WucEventUsers()
							.addUser(WucEventRole.AUTHOR,
									FarmAuthorityService.getInstance().getUserById(hourview.getHour().getCuser()), null)
							.addUser(WucEventRole.OPRETOR, getCurrentUser(session), getCurrentIp(request)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 继续学习
	 * 
	 * @return
	 */
	@RequestMapping("/PubContinue")
	public ModelAndView continueLearn(String classid, String hourid, String type, HttpSession session,
			HttpServletRequest request) {
		ViewMode view = ViewMode.getInstance();
		try {
			HourView hourview = null;
			if (!classTServiceImpl.isReadAble(classid, getCurrentUser(session))) {
				throw new RuntimeException("当前用户无学习权限!");
			}
			ClassLearnView learnView = null;
			if (getCurrentUser(session) == null) {
				// 未登錄
				if (StringUtils.isBlank(hourid)) {
					hourview = classTServiceImpl.getFirstHourView(classid);
				} else {
					hourview = classTServiceImpl.getHourView(hourid);
				}
			} else {
				if (type != null && type.equals("finish")) {
					hourid = userClassServiceImpl.finishCurrentHour(classid, getCurrentUser(session));
				}
				// 已登錄(继续学习课程)
				hourview = userClassServiceImpl.startLearnClass(classid, hourid, getCurrentUser(session));
				learnView = userClassServiceImpl.getClassLearnView(classid, getCurrentUser(session));
				classTServiceImpl.freshLearUserNum(classid);
				hourview.getClassview().bind(learnView);
				// 判断是否为最后一课
				view.putAttr("islastHour", classTServiceImpl.isLastHour(hourview, learnView));
				if (learnView.getUserclass().getPstate().equals("3") && type != null && type.equals("finish")) {
					// 完成全部課程跳回首頁
					return view.returnRedirectUrl("/classweb/Pubview.do?classid=" + classid);
				}
				view.putAttr("learnView", learnView);
			}
			HourView.initClassHourAble(hourview.getClassview());
			{// 预览权限校验
				// 加载课时的预览属性
				if (learnView == null || !learnView.isLearned()) {
					// 未学习过
					if (!HourView.initHourViewAble(hourview).isViewAble()) {
						// 也不可预览
						return view.returnRedirectUrl("/classweb/Pubview.do?classid=" + classid);
					}
				}
			}
			List<ResourceView> resources = appbindObjServiceImpl.getAppResource(hourview.getHour().getId());
			List<ResourceView> classResources = appbindObjServiceImpl.getAppResource(hourview.getHour().getClassid());
			resources = mergeClassToHourResources(resources, classResources);
			view.putAttr("resources", resources);
			view.putAttr("isFavorite", favoriteObjServiceImpl.isFavorite(hourview.getHour().getId(), getCurrentUser(session)));
			// 加载课件播放资源(同时加载用户播放状态)
			loadPlayUrlAndPlayTime(view, hourview, session, request);
			// 加载课时说明
			if (hourview.getHour().getNoteid() != null) {
				String text = wdapFileServiceImpl.readFileToText(hourview.getHour().getNoteid());
				view.putAttr("text", text);
			} else {
				view.putAttr("text", null);
			}
			WcpLog.info(
					"学习课程:" + hourview.getClassview().getClasst().getName() + "/" + hourview.getHour().getTitle()
							+ (getCurrentUser(session) != null ? "【用戶】" + getCurrentUser(session).getName() : "【匿名】"),
					null, null);
			return view.putAttr("hourview", hourview).returnModelAndView("web-simple/hour/hour-view");
		} catch (Exception e) {
			return view.setError(e.getMessage(), e).returnModelAndView("web-simple/simple-500");
		}
	}

	/**
	 * 如果課時的資源中沒有某種類型的資源，就從課程資源中加載（保證課時資源的豐富程度）
	 * 
	 * @param hourResources
	 * @param classResources
	 * @return
	 */
	private List<ResourceView> mergeClassToHourResources(List<ResourceView> hourResources,
			List<ResourceView> classResources) {
		Set<String> hasType = new HashSet<String>();
		for (ResourceView view : hourResources) {
			hasType.add(view.getResourcetype());
		}
		for (ResourceView view : classResources) {
			if (!hasType.contains(view.getResourcetype())) {
				hourResources.add(view);
			}
		}
		return hourResources;
	}
}
